<template>
  <div class="app-container">
    <el-form ref="form" label-width="120px">
       <el-form-item label="父分类id">
        <!-- 子组件 -->
        <cascader-category @getPid="getchildPid" :allCategory="allCategory" :selectedOptions="selectedOptions"></cascader-category>    
       </el-form-item>
      <el-form-item label="分类名称">
        <el-input v-model="name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">添加</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addCatetory, selectAllCatetory } from '@/api/category'
import cascaderCategory from '@/components/CascaderCategory'
export default {
  data() {
    return {
      pid: '',
      name: '',
      selectedOptions: [],
      allCategory: [],
      allCategoryTemp: []

    }
  },
  components: { cascaderCategory },
  created() {
    this.selectCategory()
  },
  methods: {
    onSubmit() {
      addCatetory(this.pid, this.name)
        .then(response => {
          this.$message(response.data.msg)
          this.selectCategory()
        })
        .catch(error => {
          console.log(error)
        })
    },
    onCancel() {
      this.$message({
        message: 'cancel!',
        type: 'warning'
      })
    },
    getchildPid(pid) {
      this.pid = pid
    },
    selectCategory() {
      selectAllCatetory()
        .then(response => {
          var result = response.data
          // console.log(result)
          if (result.errcode === 0) { this.allCategoryTemp = result.data } else { this.$message(response.data.msg) }
          // console.log(this.allCategoryTemp)
          this.allCategory = this.handleCategoryData(this.allCategoryTemp, 0)
          // console.log(JSON.stringify(this.allCategory))
        })
        .catch(error => {
          console.log(error)
        })
    },
    handleCategoryData(data, pid) {
      var result = []
      var temp
      for (var i = 0; i < data.length; i++) {
        if (data[i].pid === pid) {
          var obj = { 'label': data[i].name, 'value': data[i].id }
          temp = this.handleCategoryData(data, data[i].id)
          if (temp.length > 0) {
            obj.children = temp
          }
          result.push(obj)
        }
      }
      return result
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
</style>

